import {Platform, Alert} from 'react-native';
import {upgrade} from 'rn-app-upgrade';
import {getVersion} from 'react-native-device-info';

/**
 * app版本检测
 */
const AppUpgrade = () => {
  const app = {
    // 线上版本号
    onlineVersion: '1.0',
    // 本地版本号
    localVersion: getVersion(),
    // 下载apkUrl
    apkUrl: 'http://apk.start6.cn/app-release.apk',
  };
  // android
  if (Platform.OS === 'android') {
    if (app.onlineVersion && app.localVersion) {
      if (cpr_version(app.onlineVersion, app.localVersion)) {
        Alert.alert('发现新版本', '是否更新版本?', [
          {text: '更新', onPress: () => NewVersionDown(app.apkUrl)},
          {text: '取消', onPress: () => {}},
        ]);
      }
    } else if (Platform.OS === 'ios') {
    }
  }
};
/**
 * 下载新版本
 */
const NewVersionDown = (apkUrl) => {
  upgrade(apkUrl);
};

const toNum = (a) => {
  a = a.toString();
  //也可以这样写 var c=a.split(/\./);
  const c = a.split('.');
  const num_place = ['', '0', '00', '000', '0000'],
    r = num_place.reverse();
  for (var i = 0; i < c.length; i++) {
    const len = c[i].length;
    c[i] = r[len] + c[i];
  }
  const res = c.join('');
  return res;
};
const cpr_version = (a, b) => {
  const _a = toNum(a);
  const _b = toNum(b);
  if (_a > _b) {
    return true;
  }
  return false;
};

export {AppUpgrade};
